<template>
  <div class="order-con table-gl-w">
    <div class="search-w">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getList">
        <template #headerRight>
          <a-popover content="导出库存">
            <a-button type="text" style="font-size: 16px; color: #141840">
              <template #icon>
                <icon-download />
              </template>
            </a-button>
          </a-popover>
        </template>
        <template #headerLeft>
          <a-button style="margin-right: 10px" class="gray-outline" :loading="updateSalemanLoading" @click="updateSalerman">更新商品所属运营</a-button>
        </template>
        <template #tableBody>
          <a-table size="mini" class="table-two-line" v-model:selectedKeys="selectIds" @sorter-change="sortChange" :row-selection="rowSelection" row-key="id" :data="dataList" :loading="loading" :summary="summary" :pagination="false" :scroll="{ y: '100%' }">
            <template #columns>
              <a-table-column title="序号" #cell="{ record, rowIndex }" :width="40" fixed="left">
                {{ rowIndex + 1 }}
              </a-table-column>
              <a-table-column title="日期" #cell="{ record, rowIndex }" :width="100" fixed="left">
                <!-- {{ $setTime(record.gmtCreate) }} -->
                {{ record.date }}
              </a-table-column>
              <a-table-column title="店铺" #cell="{ record, rowIndex }" :width="100" fixed="left">
                {{ record.shopName }}
              </a-table-column>
              <a-table-column title="销售员" #cell="{ record, rowIndex }" :width="60" fixed="left">
                {{ record.salesmanName }}
              </a-table-column>
              <a-table-column title="FNSKU" #cell="{ record, rowIndex }" fixed="left" :width="80" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="startingWarehouseBalance">
                {{ record.fnsku }}
              </a-table-column>
              <a-table-column title="图片" #cell="{ record, rowIndex }" :width="60" data-index="productImg" fixed="left">
                <ImgPopover :src="record.productImg">
                  <template #con>
                    <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                  </template>
                </ImgPopover>
              </a-table-column>
              <a-table-column title="产品SKU" :width="80">
                <template #cell="{ record }">
                  <ShowSpuDetailBySku :val="record.sku" :showLimit="true" :rows="2" />
                </template>
              </a-table-column>
              <a-table-column title="sellerSKU" #cell="{ record, rowIndex }" :width="100">
                {{ record.msku }}
              </a-table-column>
              <a-table-column title="ASIN" #cell="{ record, rowIndex }" :width="100">
                {{ record.asin }}
              </a-table-column>
              <a-table-column title="事件类型" #cell="{ record, rowIndex }" :width="100">
                {{ record.eventType }}
              </a-table-column>
              <a-table-column title="参考号" #cell="{ record, rowIndex }" :width="100" data-index="referenceId">
                {{ record.referenceId }}
              </a-table-column>
              <a-table-column title="数量" #cell="{ record, rowIndex }" :width="100" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="quantity">
                {{ record.quantity }}
              </a-table-column>
              <a-table-column title="仓库ID" #cell="{ record, rowIndex }" :width="100">
                {{ record.fulfillmentCenter }}
              </a-table-column>
              <a-table-column title="库存属性" #cell="{ record, rowIndex }" :width="100">
                {{ record.disposition }}
              </a-table-column>
              <a-table-column title="原因" #cell="{ record, rowIndex }" :width="100">
                {{ record.reason }}
              </a-table-column>
              <a-table-column title="已调整数" #cell="{ record, rowIndex }" :width="100">
                {{ record.reconciledQuantity }}
              </a-table-column>
              <a-table-column title="未调整数" #cell="{ record, rowIndex }" :width="100">
                {{ record.unreconciledQuantity }}
              </a-table-column>
              <a-table-column title="具体时间" #cell="{ record, rowIndex }" :width="100">
                <!-- {{ $setTime(record.gmtSnapshotDate) }} -->
                {{ record.dateAndTime }}
              </a-table-column>
              <a-table-column title="位置" #cell="{ record, rowIndex }" :width="100">
                {{ record.location }}
              </a-table-column>
            </template>

            <template #summary-cell="{ column, record, rowIndex }">
              <div>{{ record[column.dataIndex] }}</div>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs } from 'vue'
  import { findShopListByShare } from '@/api/warehouse'
  import { getOrganizesUser } from '@/api/system'
  import { getCategoryList } from '@/api/product'
  import { Message } from '@arco-design/web-vue'
  import { findLedgerDetailViewPage, sumLedgerDetailViewByParam, updateLedgerDetailViewSalesman } from '@/api/inventory'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import dayjs from 'dayjs'
  import _ from 'lodash-es'
  export default defineComponent({
    components: {
      FilterTable,
      TableWrap,
    },
    setup() {
      const data: any = reactive({
        filterItem: [
          {
            key: 'shopIds',
            label: '选择店铺',
            value: ref(),
            type: 'select_multiple',
            width: 160,
            optionItems: [],
          },
          {
            key: 'salesmanId',
            label: '销售员',
            value: ref(),
            type: 'select',
            width: 160,
            optionItems: [],
          },
          {
            type: 'input_keyword',
            key: 'fnskus',
            keyItems: [
              { label: 'FNSKU', value: 'fnskus' },
              { label: 'sellerSku', value: 'sellerIds' },
              { label: '产品SKU', value: 'productSkus' },
            ],
            keyWidth: '90',
            value: ref(),
            placeholder: '请输入',
            label: 'FNSKU',
            width: 180,
            isMultiple: true,
          },
          {
            type: 'cascader',
            key: 'cateId',
            optionItems: [],
            keyWidth: '120',
            value: ref(),
            placeholder: '类目',
            label: '类目',
            width: 180,
            isMultiple: false,
          },
          {
            key: 'eventType',
            label: '事件类型',
            value: ref(),
            type: 'select_multiple',
            width: 160,
            optionItems: [
              { label: '配送', value: 'Shipments' },
              { label: '接收', value: 'Receipts' },
              { label: '移除', value: 'VendorReturns' },
              { label: '调拨', value: 'WhseTransfers' },
              { label: '盘点', value: 'Adjustments' },
              { label: '买家退货', value: 'CustomerReturns' },
            ],
          },
          {
            key: 'date',
            label: '日期',
            value: ref([`${dayjs().add(-1, 'month').format('YYYY-MM-DD')}`, `${dayjs().format('YYYY-MM-DD')}`]),
            type: 'date_range',
            undeletable: true,
            width: 240,
            attrs: {
              placeholder: ['开始日期', '结束日期'],
              defaultValue: [`${dayjs().add(-1, 'month').format('YYYY-MM-DD')} 00:00:00`, `${dayjs().format('YYYY-MM-DD')} 23:59:59`],
              'allow-clear': false,
            },
          },
        ],
        dataList: [],
        pageNation: { total: 0, pageSize: 20, pageNum: 1 },
        expandable: {},
        loading: false,
        selectIds: [],
        searchValue: {
          startDate: `${dayjs().add(-1, 'month').format('YYYY-MM-DD')} 00:00:00`,
          endDate: `${dayjs().format('YYYY-MM-DD')} 23:59:59`,
        },
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
        },
        summartData: {},
        updateSalemanLoading: false,
      })
      const searchByVal = (info: any) => {
        console.log(info)
        let obj = _.cloneDeep(info)
        data.searchValue = {}
        data.searchValue = info
        console.log(obj.date[0].split(' '))

        if (obj.date && obj.date[0].split(' ').length <= 1) {
          data.searchValue.startDate = `${obj['date'][0]} 00:00:00`
          data.searchValue.endDate = `${obj['date'][1]} 23:59:59`
        } else {
          data.searchValue.startDate = `${dayjs().add(-1, 'month').format('YYYY-MM-DD')} 00:00:00`
          data.searchValue.endDate = `${dayjs().format('YYYY-MM-DD')} 23:59:59`
        }
        delete data.searchValue.date
        data.pageNation.pageNum = 1
        getSummartData()
        getList()
      }
      const changePage = (val: number) => {
        data.pageNation.pageNum = val
        getList()
      }

      const sizeChange = (val: number) => {
        data.pageNation.pageNum = 1
        data.pageNation.pageSize = val
        getList()
      }

      const getShopListByShare = async () => {
        const res = await findShopListByShare({ share: false })
        let arr = res?.data
        arr.map((e: any) => {
          e.label = e.shopName
          e.value = e.id
        })
        data.filterItem[0].optionItems = arr
      }

      const summary = () => {
        console.log(data.summartData, 'data.summartData')

        let obj = {
          quantity: 0,
        }

        obj.quantity = data.summartData?.quantity || 0

        return [
          {
            referenceId: '合计',
            ...obj,
          },
        ]
      }

      // 获取用户列表
      const getUSerList = async () => {
        let params = {
          depart: false,
          pageNum: 1,
          pageSize: 1000,
        }
        const res: any = await getOrganizesUser(params)
        if (res.code == 'SUCCESS') {
          let arr = res.data?.records
          arr.map((e: any) => {
            e.label = e.userName
            e.value = e.id
            return e
          })
          data.filterItem[1].optionItems = arr
        }
      }

      const getList = async () => {
        console.log(data.searchValue)

        let params = {
          ...data.searchValue,
          pageNum: data.pageNation.pageNum,
          pageSize: data.pageNation.pageSize,
        }
        data.loading = true
        const res = await findLedgerDetailViewPage(params)
        data.dataList = res?.data?.records
        data.pageNation.total = res?.data?.total
        data.loading = false
      }

      const getSummartData = async () => {
        let params = {
          ...data.searchValue,
        }
        const res = await sumLedgerDetailViewByParam(params)

        data.summartData = res.data || {}
      }

      const sortChange = (item: any, extra: any) => {
        if (extra) {
          data.searchValue.sortField = item
          data.searchValue.sortType = extra == 'ascend' ? '1' : '-1'
        } else {
          data.searchValue.sortField = ''
          data.searchValue.sortType = ''
        }
        getList()
      }

      const getCategory = async () => {
        const res: any = await getCategoryList()
        data.filterItem[3].optionItems = res.data
      }

      const updateSalerman = async () => {
        if (data.selectIds.length <= 0) {
          return Message.error('请先选择需要操作的数据')
        }
        data.updateSalemanLoading = true
        try {
          const res: any = await updateLedgerDetailViewSalesman({ ids: data.selectIds })
          if (res.code == 'SUCCESS') {
            Message.success('更新成功')
          }
          data.selectIds = []
          data.updateSalemanLoading = false
        } catch (error) {
          data.updateSalemanLoading = false
        }
      }

      getCategory()
      getSummartData()
      getShopListByShare()
      getUSerList()
      getList()

      return {
        ...(toRefs(data) as any),
        searchByVal,
        changePage,
        sizeChange,
        sortChange,
        summary,
        updateSalerman,
        getList,
      }
    },
  })
</script>

<style lang="less" scoped>
  .order-con {
    height: calc(100vh - @menuHeight);
    width: 100%;

    :deep(.arco-table-cell-align-left) {
      padding: 0 !important;
    }

    .item-detail {
      min-height: 56px;
      width: 100%;
      border-bottom: 1px solid #e5e6eb;
    }
  }
</style>
